import requests
import time

from conf import settings
from plugins.create_password import generate_secure_password

logfile_error = settings.LOG_PATH_E
logfile_success = settings.LOG_PATH_S

def seweb_login(login_url, login_data):
    access_token = None
    try:
        response = requests.post(login_url, json=login_data)
        token = response.json()['data']['access']
        access_token = {'Authorization': f"JWT {token}"}
        return access_token
    except Exception as e:
        message = "Failed login seweb:" + str(e)
        return message

def seweb_logout(logout_url, token):
    try:
        response = requests.post(logout_url, headers=token)
        message = response.json()['msg']
        return message
    except Exception as e:
        message = "Failed logout from seweb:" + str(e)
        return message
    
def cmdb_get_srvaccount(url, token):
    srv_account = []
    try:
        account_get_url = url + '?limit=999'
        response = requests.get(account_get_url, headers=token)
        user_all = response.json()['data']
        for user in user_all:
            id = user['id']
            server_ip = user['server_ip']
            account = user['account']
            current_passwd = user['current_passwd']
            last_passwd = user['last_passwd']
            next_passwd = user['next_passwd']
            last_change = user['last_change']
            next_change = user['next_change']
            is_change = user['is_change']

            srv_account.append({'id': id, 'server_ip': server_ip, 'account': account, 
                                'current_passwd': current_passwd, 'last_passwd': last_passwd, 'next_passwd': next_passwd,
                                'last_change': last_change, 'next_change': next_change, 'is_change': is_change})
            
        return srv_account
    except Exception as e:
        message = "Failed to get cmdb srvaccount data:" + str(e)
        return message
    
def srvaccount_update(userdata, url, token, log_path):
    results = []
    for id, user in userdata:
        try:
            update_url = f"{url}{id}/"
            response = requests.put(update_url, headers=token, json=user)
            results.append((id, response))
        except Exception as e:
            message = 'Failed to update: ' + user['name'] + ' ' + str(e)
            with open(log_path, 'ab') as f:
                    log = 'Time:%s \t API:%s \t Result:%s \n' % (time.strftime('%Y-%m-%d %H:%M:%S'),url, message)
                    f.write(log.encode())
    return results

def changed_account_update(userdata, url, token):
    for user in userdata:
        try:
            user_id = user['id']
            user_data = user.copy()
            user_data.pop('id')

            update_url = f"{url}{user_id}/"
            requests.put(update_url, headers=token, json=user_data)

        except Exception as e:
            log_message = (
                    f"[FAILED_CMDB] 密码更新失败！服务器: {user['server_ip']} 账户: {user['account']} "
                    f"错误: {str(e)}"
                )
            with open(logfile_error, 'a', encoding='utf-8') as f:
                log = f'Time:{time.strftime("%Y-%m-%d %H:%M:%S")} \t Result:{log_message}\n'
                f.write(log)







